package zenupdaterapp.ui;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import zenupdaterapp.customTypes.FullUpdateInfo;
import zenupdaterapp.customTypes.UpdateInfo;
import zenupdaterapp.customization.Customization;
import zenupdaterapp.listadapters.UpdateListAdapter;
import zenupdaterapp.misc.Constants;
import zenupdaterapp.misc.Log;
import zenupdaterapp.misc.State;
import zenupdaterapp.tasks.AppUpdateCheckTask;
import zenupdaterapp.tasks.ChangelogTask;
import zenupdaterapp.tasks.MD5CheckerTask;
import zenupdaterapp.tasks.UpdateCheckTask;
import zenupdaterapp.tasks.ChangelogTask.ChangelogType;
import zenupdaterapp.utils.Preferences;
import zenupdaterapp.utils.StringUtils;
import zenupdaterapp.utils.SysUtils;
import zenupdaterapp.utils.UpdateFilter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    //Dialogs
    private static final int DIALOG_NO_SDCARD = 1;
    private static final int DIALOG_OVERWRITE_UPDATE = 2;
    private static final int DIALOG_DELETE_EXISTING = 3;
    private static final int DIALOG_RUNNING_OLD_VERSION = 4;
    private static final int DIALOG_NO_MD5 = 5;
    private static final int DIALOG_ABOUT = 6;
    private static final int DIALOG_NO_SDCARD_START = 7;
    private static final int DIALOG_OLD_APP_FILES = 8;
    private static final int DIALOG_FIRST_START = 9;
    private static final int DIALOG_LOG_COLLECTOR_NOT_INSTALLED = 10;
    private static final int DIALOG_BUG_REPORTER_SEND_LOG = 11;
    private static final int DIALOG_DUAL_DONATION = 12;

    private Boolean showDebugOutput = false;

    private Spinner mUpdatesSpinner;
    private Spinner mThemesSpinner;
    private Spinner mExtrasSpinner;
    private Spinner mExistingUpdatesSpinner;
    private File mUpdateFolder;
    private File mDataFolder;
    private ViewFlipper flipper;
    private Preferences prefs;
    private Boolean runningOldVersion = false;
    private AsyncTask<File, Void, Boolean> md5CheckerTask;
    private File foo;
    private UpdateInfo updateForDownload;
    private String existingUpdateFilename;
    private String existingUpdateFilenotes;
    private String mAdditonalInfo;
    private UpdateListAdapter<UpdateInfo> spAdapterRoms;
    private UpdateListAdapter<UpdateInfo> spAdapterThemes;
	private UpdateListAdapter<UpdateInfo> spAdapterExtras;
    private ArrayAdapter<String> localUpdates;
    private static Resources res;

    public void ListenerScreenshotThemes(View target) {
        if (showDebugOutput) Log.d(TAG, "Theme Screenshot Button clicked");
        final UpdateInfo ui = (UpdateInfo) mThemesSpinner.getSelectedItem();
        Intent i = new Intent(MainActivity.this, ScreenshotActivity.class);
        i.putExtra(Constants.SCREENSHOTS_UPDATE, (Serializable) ui);
        startActivity(i);
        return;
    }

    public void ListenerDownloadUpdateButton(View target) {
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD);
            return;
        }
        if (showDebugOutput) Log.d(TAG, "Download Rom Button clicked");
        updateForDownload = (UpdateInfo) mUpdatesSpinner.getSelectedItem();
        //Check if the File is present, so prompt the User to overwrite it
        foo = new File(mUpdateFolder + "/" + updateForDownload.getFileName());
        if (foo.isFile() && foo.exists()) {

            showDialog(DIALOG_OVERWRITE_UPDATE);
            return;
        }
        //Otherwise download it
        else {
            downloadRequestedUpdate(updateForDownload);
        }
    }
    
    public void ListenerDownloadExtrasButton(View target) {
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD);
            return;
        }
        if (showDebugOutput) Log.d(TAG, "Download Extras Button clicked");
        updateForDownload = (UpdateInfo) mExtrasSpinner.getSelectedItem();
        //Check if the File is present, so prompt the User to overwrite it
        foo = new File(mUpdateFolder + "/" + updateForDownload.getFileName());
        if (foo.isFile() && foo.exists()) {

            showDialog(DIALOG_OVERWRITE_UPDATE);
            return;
        }
        //Otherwise download it
        else {
            downloadRequestedUpdate(updateForDownload);
        }
    }

    public void ListenerDownloadThemeButton(View target) {
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD);
            return;
        }

        if (showDebugOutput) Log.d(TAG, "Download Theme Button clicked");
        updateForDownload = (UpdateInfo) mThemesSpinner.getSelectedItem();
        //Check if the File is present, so prompt the User to overwrite it
        foo = new File(mUpdateFolder + "/" + updateForDownload.getFileName());
        if (foo.isFile() && foo.exists()) {
            showDialog(DIALOG_OVERWRITE_UPDATE);
            return;
        }
        //Otherwise download it
        else {
            downloadRequestedUpdate(updateForDownload);
        }
    }

    public void ListenerUpdateChangelogButton(View target) {
        if (showDebugOutput) Log.d(TAG, "Rom Changelog Button clicked");
        getChangelog(ChangelogType.ROM);
    }

    public void ListenerThemeChangelogButton(View target) {
        if (showDebugOutput) Log.d(TAG, "Theme Changelog Button clicked");
        getChangelog(ChangelogType.THEME);
    }
    
    public void ListenerExtrasChangelogButton(View target) {
        if (showDebugOutput) Log.d(TAG, "Extras Changelog Button clicked");
        getChangelog(ChangelogType.EXTRAS);
    }

    public void ListenerDeleteUpdatesButton(View target) {
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD);
            return;
        } else {
            showDialog(DIALOG_DELETE_EXISTING);
        }
    }

    public void ListenerApplyExistingButton(View target) {
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD);
            return;
        }

        if (runningOldVersion) {
            showDialog(DIALOG_RUNNING_OLD_VERSION);
        }

        existingUpdateFilename = (String) mExistingUpdatesSpinner.getSelectedItem();
        existingUpdateFilenotes = (String) res.getString(R.string.apply_upload_info_message);
        if (showDebugOutput) Log.d(TAG, "Selected to Apply Existing update: " + existingUpdateFilename);
        File Update = new File(mUpdateFolder + "/" + existingUpdateFilename);
        File MD5 = new File(mUpdateFolder + "/" + existingUpdateFilename + ".md5sum");
        //IF no MD5 exists, ask the User what to do
        if (!MD5.exists() || !MD5.canRead()) {
            showDialog(DIALOG_NO_MD5);
        }
        //If MD5 exists, apply the update normally
        else {
            Resources res = getResources();
            ProgressDialog progressDialog = ProgressDialog.show(
                    MainActivity.this,
                    res.getString(R.string.verify_and_apply_dialog_title),
                    res.getString(R.string.verify_and_apply_dialog_message),
                    true,
                    true,
                    new DialogInterface.OnCancelListener() {
                        public void onCancel(DialogInterface arg0) {
                            if (md5CheckerTask != null)
                                md5CheckerTask.cancel(true);
                        }
                    }
            );

            md5CheckerTask = new MD5CheckerTask(this, progressDialog, existingUpdateFilename, existingUpdateFilenotes, showDebugOutput).execute(Update);
        }
    }

    public void ListenerFlipperButton(View target) {
    	int id = target.getId();
    	int child = -1;
    	switch (id) {
	    	case R.id.button_available_updates:
	    		child = Constants.FLIPPER_AVAILABLE_UPDATES;
	    		break;
	    	case R.id.button_available_themes:
	    		child = Constants.FLIPPER_AVAILABLE_THEMES;
	    		break;
	    	case R.id.button_available_extras:
	    		child = Constants.FLIPPER_AVAILABLE_EXTRAS;
	    		break;
	    	case R.id.button_existing_updates:
	    		child = Constants.FLIPPER_EXISTING_UPDATES;
	    		break;
	    	default:
	    		return;
    	}
    	if (flipper.getDisplayedChild() != child)
            flipper.setDisplayedChild(child);
    }

    private final Spinner.OnItemSelectedListener mUpdateSpinnerChanged = new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Button updateChangelogButton = (Button) findViewById(R.id.show_changelog_button);
            List<String> changelog = ((UpdateInfo) mUpdatesSpinner.getSelectedItem()).getDescription();
            if (changelog == null || changelog.size() == 0) {
                updateChangelogButton.setVisibility(View.GONE);
            } else {
                updateChangelogButton.setVisibility(View.VISIBLE);
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    };
    
    private final Spinner.OnItemSelectedListener mExtrasSpinnerChanged = new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Button extrasChangelogButton = (Button) findViewById(R.id.show_extras_changelog_button);
            List<String> changelog = ((UpdateInfo) mExtrasSpinner.getSelectedItem()).getDescription();
            if (changelog == null || changelog.size() == 0) {
                extrasChangelogButton.setVisibility(View.GONE);
            } else {
                extrasChangelogButton.setVisibility(View.VISIBLE);
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    };

    private final Spinner.OnItemSelectedListener mThemeSpinnerChanged = new Spinner.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Button themeChangelogButton = (Button) findViewById(R.id.show_theme_changelog_button);
            Button ScreenshotThemeButton = (Button) findViewById(R.id.theme_screenshots_button);
            UpdateInfo item = (UpdateInfo) mThemesSpinner.getSelectedItem();
            List<String> changelog = item.getDescription();
            List<URI> screenshots = item.screenshots;
            int ScreenshotCount = item.screenshots.size();

            if (changelog == null || changelog.size() == 0) {
                themeChangelogButton.setVisibility(View.GONE);
            } else {
                themeChangelogButton.setVisibility(View.VISIBLE);
            }
            if (screenshots == null || ScreenshotCount < 1) {
                ScreenshotThemeButton.setVisibility(View.GONE);
            } else {
                ScreenshotThemeButton.setVisibility(View.VISIBLE);
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        prefs = new Preferences(this);
        res = getResources();

        //Debug Output
        showDebugOutput = prefs.displayDebugOutput();

        if (showDebugOutput) Log.d(TAG, "onCreate called");
        
        //Check For Sdcard
        if (!Environment.MEDIA_MOUNTED.equalsIgnoreCase(Environment.getExternalStorageState())) {
            showDialog(DIALOG_NO_SDCARD_START);
            if (showDebugOutput) Log.i(TAG, "SDcard Not Available");
        } else {
        	if (showDebugOutput) Log.i(TAG, "SDcard Available");
        }

        //Check for App Updates
        if (Customization.AppUpdatesupport) {
        	if (prefs.AppUpdateCheck()) {
        		AppUpdateCheckTask.StartCheck(this, showDebugOutput);
        	}
    	}
        
        //Check and Delete old App Data on New Install
        if (Customization.AppUpdatesupport) {
        	if (prefs.getAppDataWipePref()) {
        		checkForOldAppData();
        	}
    	}
        
        //Show First Start Dialog
        if (prefs.getAppFirstStart()) {
        	prefs.setAppFirstStartFalse();
        	showDialog(DIALOG_FIRST_START);
    	}

        //Set Content View
        setContentView(R.layout.main);
        
        //Inflate the Existing View
        findViewById(R.id.main_stub_existing).setVisibility(View.VISIBLE);

        //Inflate the Screenshot View if enabled
        if (Customization.Themessupport) {
            findViewById(R.id.main_stub_themes).setVisibility(View.VISIBLE);
        }
        
        //Inflate the Extras View if enabled
        if (Customization.Extrassupport) {
            findViewById(R.id.main_stub_extras).setVisibility(View.VISIBLE);
        }

        //Layout
        flipper = (ViewFlipper) findViewById(R.id.Flipper);
        //Make the Screenshot Button invisible
        if (!Customization.Themessupport) {
        	Button btnAvailableThemes = (Button) findViewById(R.id.button_available_themes);
            btnAvailableThemes.setVisibility(View.GONE);
        }
        
        //Make the Extras Button invisible
        if (!Customization.Extrassupport) {
        	Button btnAvailableExtras = (Button) findViewById(R.id.button_available_extras);
            btnAvailableExtras.setVisibility(View.GONE);
        }
        
        mUpdatesSpinner = (Spinner) findViewById(R.id.available_updates_list);
        mUpdatesSpinner.setOnItemSelectedListener(mUpdateSpinnerChanged);
        spAdapterRoms = new UpdateListAdapter<UpdateInfo>(
                this,
                new ArrayList<UpdateInfo>());
        spAdapterRoms.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spAdapterRoms.setNotifyOnChange(false);
        mUpdatesSpinner.setAdapter(spAdapterRoms);

        if (Customization.Themessupport) {
        	mThemesSpinner = (Spinner) findViewById(R.id.available_themes_list);
        	mThemesSpinner.setOnItemSelectedListener(mThemeSpinnerChanged);
            spAdapterThemes = new UpdateListAdapter<UpdateInfo>(
                    this,
                    new ArrayList<UpdateInfo>());
            spAdapterThemes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spAdapterThemes.setNotifyOnChange(false);
            mThemesSpinner.setAdapter(spAdapterThemes);
        }

		if (Customization.Extrassupport) {
        	mExtrasSpinner = (Spinner) findViewById(R.id.available_extras_list);
        	mExtrasSpinner.setOnItemSelectedListener(mExtrasSpinnerChanged);
            spAdapterExtras = new UpdateListAdapter<UpdateInfo>(
                    this,
                    new ArrayList<UpdateInfo>());
            spAdapterExtras.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spAdapterExtras.setNotifyOnChange(false);
            mExtrasSpinner.setAdapter(spAdapterExtras);
        }

        mExistingUpdatesSpinner = (Spinner) findViewById(R.id.found_updates_list);
        localUpdates = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_spinner_item,
                new ArrayList<String>());
        localUpdates.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        localUpdates.setNotifyOnChange(false);
        mExistingUpdatesSpinner.setAdapter(localUpdates);

        String mod = SysUtils.getModVersion();
        runningOldVersion = StringUtils.compareVersions(Customization.MIN_SUPPORTED_VERSION_STRING, mod);
    }

    @Override
    protected void onStart() {
        if (showDebugOutput) Log.d(TAG, "onStart called");
        super.onStart();

        //Show a Dialog that the User runs an old rom.
        if (runningOldVersion) {
            showDialog(DIALOG_RUNNING_OLD_VERSION);
            return;
        }
    }

    @Override
    protected void onResume() {
        if (showDebugOutput) Log.d(TAG, "onResume called");
        super.onResume();

        try {
            if (DownloadActivity.myService != null && DownloadActivity.myService.DownloadRunning()) {
                UpdateInfo ui = DownloadActivity.myService.getCurrentUpdate();
                Intent i = new Intent(MainActivity.this, DownloadActivity.class);
                i.putExtra(Constants.KEY_UPDATE_INFO, (Serializable) ui);
                startActivity(i);
            } else {
            	updateLayout();
            }
        }
        catch (RemoteException e) {
            Log.e(TAG, "Exception on calling DownloadService", e);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, Constants.MENU_ID_UPDATE_NOW, Menu.NONE, R.string.menu_check_now)
                .setIcon(R.drawable.check_now);
        menu.add(Menu.NONE, Constants.MENU_ID_CONFIG, Menu.NONE, R.string.menu_config)
                .setIcon(R.drawable.button_config);
        menu.add(Menu.NONE, Constants.MENU_ID_ABOUT, Menu.NONE, R.string.menu_about)
                .setIcon(R.drawable.button_about);
        menu.add(Menu.NONE, Constants.MENU_ID_CHANGELOG, Menu.NONE, R.string.menu_changelog)
                .setIcon(R.drawable.button_clog);
        	if (Customization.AppUpdatesupport) {
        menu.add(Menu.NONE, Constants.MENU_ID_APP_UPDATE_CHECK, Menu.NONE, R.string.menu_app_update_check)
        		.setIcon(R.drawable.download); }
        	if (Customization.BugReportsupport) {
        menu.add(Menu.NONE, Constants.MENU_ID_SEND_LOG, Menu.NONE, R.string.menu_bug_reporter)
				.setIcon(R.drawable.send_log); }
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean superReturn = super.onPrepareOptionsMenu(menu);

        try {
            if (DownloadActivity.myService != null && DownloadActivity.myService.DownloadRunning()) {
                //Download in progress
                menu.findItem(Constants.MENU_ID_UPDATE_NOW).setEnabled(false);
            }
        }
        catch (RemoteException e) {
            Log.e(TAG, "Exception on calling DownloadService", e);
        }
        return superReturn;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case Constants.MENU_ID_UPDATE_NOW:
                checkForUpdates(null);
                return true;
            case Constants.MENU_ID_CONFIG:
                showConfigActivity();
                return true;
            case Constants.MENU_ID_ABOUT:
                showDialog(DIALOG_ABOUT);
                return true;
            case Constants.MENU_ID_CHANGELOG:
                getChangelog(ChangelogType.APP);
                return true;
            case Constants.MENU_ID_APP_UPDATE_CHECK:
            	AppUpdateCheckTask.ManualCheck(this, showDebugOutput);
            	return true;
            case Constants.MENU_ID_SEND_LOG:
            	collectAndSendLog();
            	return true;
            default:
                Log.e(TAG, "Unknown Menu ID:" + item.getItemId());
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    public void updateLayout() {
        FullUpdateInfo mAvailableUpdates = null;
        try {
            mAvailableUpdates = State.loadState(this, showDebugOutput);
        }
        catch (IOException e) {
            Log.e(TAG, "Unable to restore activity status", e);
        }

        //Header Mod Version layout
        View header = findViewById(R.id.header_layout);
        TextView HeaderModver = (TextView) header.findViewById(R.id.header_modver);
        
        //Rom Layout
        View roms = findViewById(R.id.rom_layout);
        View roms_footer = findViewById(R.id.roms_footer_layout);
        TextView lastRomUpdateChecktv = (TextView) roms_footer.findViewById(R.id.last_rom_update_check);
        Button selectUploadButton = (Button) roms.findViewById(R.id.download_update_button);
        TextView DownloadText = (TextView) roms.findViewById(R.id.available_updates_text);
        LinearLayout stableExperimentalInfoUpdates = (LinearLayout) roms.findViewById(R.id.stable_experimental_description_container_updates);
        Button changelogButton = (Button) roms.findViewById(R.id.show_changelog_button);
        //No ROM Updates Found Layout
        Button CheckNowUpdateChooserUpdates = (Button) roms.findViewById(R.id.check_now_button_update_chooser_updates);
        TextView CheckNowUpdateChooserTextUpdates = (TextView) roms.findViewById(R.id.check_now_update_chooser_text_updates);

        //Existing Updates Layout
        View existing = findViewById(R.id.existing_layout);
        TextView mdownloadedUpdateText = (TextView) existing.findViewById(R.id.downloaded_update_found);
        Button mdeleteOldUpdatesButton = (Button) existing.findViewById(R.id.delete_updates_button);
        Button mapplyUpdateButton = (Button) existing.findViewById(R.id.apply_update_button);
        TextView mNoExistingUpdatesFound = (TextView) existing.findViewById(R.id.no_existing_updates_found_textview);

        //Theme Layout
        View themes = null;
        View themes_footer = null;
        TextView lastThemeUpdateChecktv = null;
        Button btnDownloadTheme = null;
        TextView tvThemeDownloadText = null;
        LinearLayout stableExperimentalInfoThemes = null;
        Button btnThemechangelogButton = null;
        Button btnThemeScreenshotButton = null;
        TextView tvNoThemeUpdateServer = null;
        Button CheckNowUpdateChooserThemes = null;
        TextView CheckNowUpdateChooserTextThemes = null;
        if (Customization.Themessupport) {
            themes = findViewById(R.id.themes_layout);
            themes_footer = findViewById(R.id.themes_footer_layout);
            lastThemeUpdateChecktv = (TextView) themes_footer.findViewById(R.id.last_theme_update_check);
            btnDownloadTheme = (Button) themes.findViewById(R.id.download_theme_button);
            tvThemeDownloadText = (TextView) themes.findViewById(R.id.available_themes_text);
            stableExperimentalInfoThemes = (LinearLayout) themes.findViewById(R.id.stable_experimental_description_container_themes);
            btnThemechangelogButton = (Button) themes.findViewById(R.id.show_theme_changelog_button);
            btnThemeScreenshotButton = (Button) themes.findViewById(R.id.theme_screenshots_button);
            tvNoThemeUpdateServer = (TextView) themes.findViewById(R.id.no_theme_update_server_configured);
            //No Theme Updates Found Layout
            CheckNowUpdateChooserThemes = (Button) themes.findViewById(R.id.check_now_button_update_chooser_themes);
            CheckNowUpdateChooserTextThemes = (TextView) themes.findViewById(R.id.check_now_update_chooser_text_themes);
        }
        
        //Extras Layout
        View extras = null;
        View extras_footer = null;
        TextView lastExtrasUpdateChecktv = null;
        Button btnDownloadExtras = null;
        TextView tvExtrasDownloadText = null;
        LinearLayout stableExperimentalInfoExtras = null;
        Button btnExtraschangelogButton = null;
        Button CheckNowUpdateChooserExtras = null;
        TextView CheckNowUpdateChooserTextExtras = null;
        if (Customization.Extrassupport) {
            extras = findViewById(R.id.extras_layout);
            extras_footer = findViewById(R.id.extras_footer_layout);
            lastExtrasUpdateChecktv = (TextView) extras_footer.findViewById(R.id.last_extras_update_check);
            btnDownloadExtras = (Button) extras.findViewById(R.id.download_extras_button);
            tvExtrasDownloadText = (TextView) extras.findViewById(R.id.available_extras_text);
            stableExperimentalInfoExtras = (LinearLayout) extras.findViewById(R.id.stable_experimental_description_container_extras);
            btnExtraschangelogButton = (Button) extras.findViewById(R.id.show_extras_changelog_button);
            //No Extras Updates Found Layout
            CheckNowUpdateChooserExtras = (Button) extras.findViewById(R.id.check_now_button_update_chooser_extras);
            CheckNowUpdateChooserTextExtras = (TextView) extras.findViewById(R.id.check_now_update_chooser_text_extras);
        }

        //Read existing Updates
        List<String> existingFilenames = null;
        mUpdateFolder = new File(Environment.getExternalStorageDirectory() + "/" + prefs.getUpdateFolder());
        FilenameFilter f = new UpdateFilter(".zip");
        File[] files = mUpdateFolder.listFiles(f);
        //If Folder Exists and Updates are present(with md5files)
        if (mUpdateFolder.exists() && mUpdateFolder.isDirectory() && files != null && files.length > 0) {
            //To show only the Filename. Otherwise the whole Path with /sdcard/ZenUpdater will be shown
            existingFilenames = new ArrayList<String>();
            for (File file : files) {
                existingFilenames.add(file.getName());
            }
            //For sorting the Filenames, have to find a way to do natural sorting
            existingFilenames = Collections.synchronizedList(existingFilenames);
            Collections.sort(existingFilenames, Collections.reverseOrder());
        }
        files = null;

        //Reset all Visibilities
        if (Customization.Themessupport) {
            CheckNowUpdateChooserTextThemes.setVisibility(View.GONE);
            CheckNowUpdateChooserThemes.setVisibility(View.GONE);
        }
        
        if (Customization.Extrassupport) {
            CheckNowUpdateChooserTextExtras.setVisibility(View.GONE);
            CheckNowUpdateChooserExtras.setVisibility(View.GONE);
        }
        
        CheckNowUpdateChooserTextUpdates.setVisibility(View.GONE);
        CheckNowUpdateChooserUpdates.setVisibility(View.GONE);
        selectUploadButton.setVisibility(View.VISIBLE);
        mUpdatesSpinner.setVisibility(View.VISIBLE);
        DownloadText.setVisibility(View.VISIBLE);
        stableExperimentalInfoUpdates.setVisibility(View.VISIBLE);
        changelogButton.setVisibility(View.VISIBLE);
        if (Customization.Themessupport) {
            btnDownloadTheme.setVisibility(View.VISIBLE);
            mThemesSpinner.setVisibility(View.VISIBLE);
            tvThemeDownloadText.setVisibility(View.VISIBLE);
            stableExperimentalInfoThemes.setVisibility(View.VISIBLE);
            btnThemechangelogButton.setVisibility(View.VISIBLE);
            btnThemeScreenshotButton.setVisibility(View.VISIBLE);
        }
        
        if (Customization.Extrassupport) {
            btnDownloadExtras.setVisibility(View.VISIBLE);
            mExtrasSpinner.setVisibility(View.VISIBLE);
            tvExtrasDownloadText.setVisibility(View.VISIBLE);
            stableExperimentalInfoExtras.setVisibility(View.VISIBLE);
            btnExtraschangelogButton.setVisibility(View.VISIBLE);
        }

        //Theme Update File URL Set?
        boolean ThemeUpdateUrlSet = prefs.ThemeUpdateUrlSet();

        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(R.string.not_new_updates_found_title);

        if (Customization.Themessupport) {
            lastThemeUpdateChecktv.setText(res.getString(R.string.last_update_check_text) + ": " + prefs.getLastUpdateCheckString());
        }
        if (Customization.Extrassupport) {
            lastExtrasUpdateChecktv.setText(res.getString(R.string.last_update_check_text) + ": " + prefs.getLastUpdateCheckString());
        }
        lastRomUpdateChecktv.setText(res.getString(R.string.last_update_check_text) + ": " + prefs.getLastUpdateCheckString());
        HeaderModver.setText(res.getString(R.string.title_running) + " " + SysUtils.getModVersion());

        //Sets the Theme, Extras and Rom Variables
        List<UpdateInfo> availableRoms = null;
        List<UpdateInfo> availableThemes = null;
        List<UpdateInfo> availableExtras = null;
        if (mAvailableUpdates != null) {
            if (mAvailableUpdates.roms != null)
                availableRoms = mAvailableUpdates.roms;
            if (Customization.Themessupport && mAvailableUpdates.themes != null)
                availableThemes = mAvailableUpdates.themes;
            if (Customization.Extrassupport && mAvailableUpdates.extras != null)
                availableExtras = mAvailableUpdates.extras;
            //Add the incrementalUpdates
            if (mAvailableUpdates.incrementalRoms != null)
                availableRoms.addAll(mAvailableUpdates.incrementalRoms);
        }

        //Rom Layout
        if (availableRoms != null && availableRoms.size() > 0) {
        	spAdapterRoms.clear();
        	for (UpdateInfo rom:availableRoms) {
        		spAdapterRoms.add(rom);
        	}
        	spAdapterRoms.notifyDataSetChanged();
        } else {
            selectUploadButton.setVisibility(View.GONE);
            mUpdatesSpinner.setVisibility(View.GONE);
            DownloadText.setVisibility(View.GONE);
            stableExperimentalInfoUpdates.setVisibility(View.GONE);
            changelogButton.setVisibility(View.GONE);
            CheckNowUpdateChooserTextUpdates.setVisibility(View.VISIBLE);
            CheckNowUpdateChooserUpdates.setVisibility(View.VISIBLE);
        }

        //Disable the download Button when running an old ROM
        if (runningOldVersion)
            selectUploadButton.setEnabled(false);

        //Theme Layout
        //Update URL Set?
        if (Customization.Themessupport) {
            if (!ThemeUpdateUrlSet) {
                tvNoThemeUpdateServer.setVisibility(View.VISIBLE);
                btnDownloadTheme.setVisibility(View.GONE);
                mThemesSpinner.setVisibility(View.GONE);
                tvThemeDownloadText.setVisibility(View.GONE);
                stableExperimentalInfoThemes.setVisibility(View.GONE);
                btnThemechangelogButton.setVisibility(View.GONE);
                btnThemeScreenshotButton.setVisibility(View.GONE);
                CheckNowUpdateChooserTextThemes.setVisibility(View.GONE);
                CheckNowUpdateChooserThemes.setVisibility(View.GONE);
            }
            //Themes
            else if (availableThemes != null && availableThemes.size() > 0) {
            	spAdapterThemes.clear();
            	for (UpdateInfo theme:availableThemes) {
            		spAdapterThemes.add(theme);
            	}
            	spAdapterThemes.notifyDataSetChanged();
            }
            //No Updates Found
            else {
                btnDownloadTheme.setVisibility(View.GONE);
                mThemesSpinner.setVisibility(View.GONE);
                tvThemeDownloadText.setVisibility(View.GONE);
                stableExperimentalInfoThemes.setVisibility(View.GONE);
                btnThemechangelogButton.setVisibility(View.GONE);
                btnThemeScreenshotButton.setVisibility(View.GONE);
                CheckNowUpdateChooserTextThemes.setVisibility(View.VISIBLE);
                CheckNowUpdateChooserThemes.setVisibility(View.VISIBLE);
            }
        }
        
        //Extras Layout
        if (Customization.Extrassupport) {
            if (availableExtras != null && availableExtras.size() > 0) {
            	spAdapterExtras.clear();
            	for (UpdateInfo extra:availableExtras) {
            		spAdapterExtras.add(extra);
            	}
            	spAdapterExtras.notifyDataSetChanged();
            } else {
                btnDownloadExtras.setVisibility(View.GONE);
                mExtrasSpinner.setVisibility(View.GONE);
                tvExtrasDownloadText.setVisibility(View.GONE);
                stableExperimentalInfoExtras.setVisibility(View.GONE);
                btnExtraschangelogButton.setVisibility(View.GONE);
                CheckNowUpdateChooserTextExtras.setVisibility(View.VISIBLE);
                CheckNowUpdateChooserExtras.setVisibility(View.VISIBLE);
            }
        }

        //Existing Updates Layout
        if (existingFilenames != null && existingFilenames.size() > 0) {
        	localUpdates.clear();
        	for (String file:existingFilenames) {
        		localUpdates.add(file);
        	}
        	localUpdates.notifyDataSetChanged();
        } else {
            mNoExistingUpdatesFound.setVisibility(View.VISIBLE);
            mExistingUpdatesSpinner.setVisibility(View.GONE);
            mapplyUpdateButton.setVisibility(View.GONE);
            mdownloadedUpdateText.setVisibility(View.GONE);
            mdeleteOldUpdatesButton.setVisibility(View.GONE);
        }
    }

    private void getChangelog(ChangelogType changelogType) {
        switch (changelogType) {
            case ROM:
                //Get the ROM Changelog and Display the Changelog
            	UpdateInfo uiRom = (UpdateInfo) mUpdatesSpinner.getSelectedItem();
            	new ChangelogTask(this).execute(changelogType, uiRom);
                break;
            case THEME:
                //Get the THEME Changelog and Display the Changelog
            	UpdateInfo uiTheme = (UpdateInfo) mThemesSpinner.getSelectedItem();
            	new ChangelogTask(this).execute(changelogType, uiTheme);
                break;
            case EXTRAS:
                //Get the EXTRAS Changelog and Display the Changelog
            	UpdateInfo uiExtras = (UpdateInfo) mExtrasSpinner.getSelectedItem();
            	new ChangelogTask(this).execute(changelogType, uiExtras);
                break;
            case APP:
            	new ChangelogTask(this).execute(changelogType);
                break;
            default:
                return;
        }
    }

    private void showConfigActivity() {
        Intent i = new Intent(this, ConfigActivity.class);
        startActivity(i);
    }

    public void checkForUpdates(View target) {
        //Refresh the Layout when UpdateCheck finished
        UpdateCheckTask task = new UpdateCheckTask(this, showDebugOutput);
        task.execute((Void) null);
        updateLayout();
    }

    private void downloadRequestedUpdate(UpdateInfo ui) {
        Intent i = new Intent(MainActivity.this, DownloadActivity.class);
        i.putExtra(Constants.KEY_UPDATE_INFO, (Serializable) ui);
        startActivity(i);
        Toast.makeText(this, R.string.downloading_update, Toast.LENGTH_LONG).show();
    }

    private boolean deleteOldUpdates() {
        boolean success;
        //updateFolder: Foldername
        //mUpdateFolder: Foldername with fullpath of SDCARD
        String updateFolder = prefs.getUpdateFolder();
        if (mUpdateFolder.exists() && mUpdateFolder.isDirectory() && !updateFolder.trim().equals("") && !updateFolder.trim().equals("/")) {
            deleteDir(mUpdateFolder);
            mUpdateFolder.mkdir();
            if (showDebugOutput) Log.d(TAG, "Updates deleted and UpdateFolder created again");
            success = true;
            Toast.makeText(this, R.string.delete_updates_success_message, Toast.LENGTH_LONG).show();
        } else if (!mUpdateFolder.exists()) {
            success = false;
            Toast.makeText(this, R.string.delete_updates_noFolder_message, Toast.LENGTH_LONG).show();
        } else if (updateFolder.trim().equals("") || updateFolder.trim().equals("/")) {
            success = false;
            Toast.makeText(this, R.string.delete_updates_root_folder_message, Toast.LENGTH_LONG).show();
        } else {
            success = false;
            Toast.makeText(this, R.string.delete_updates_failure_message, Toast.LENGTH_LONG).show();
        }
        return success;
    }

    private boolean deleteUpdate(String filename) {
        boolean success = false;
        if (mUpdateFolder.exists() && mUpdateFolder.isDirectory()) {
            File ZIPfiletodelete = new File(mUpdateFolder + "/" + filename);
            File MD5filetodelete = new File(mUpdateFolder + "/" + filename + ".md5sum");
            if (ZIPfiletodelete.exists()) {
                ZIPfiletodelete.delete();
            } else {
                if (showDebugOutput) Log.d(TAG, "Update to delete not found");
                if (showDebugOutput) Log.d(TAG, "Zip File: " + ZIPfiletodelete.getAbsolutePath());
                return false;
            }
            if (MD5filetodelete.exists()) {
                MD5filetodelete.delete();
            } else {
                if (showDebugOutput) Log.d(TAG, "MD5 to delete not found. No Problem here.");
                if (showDebugOutput) Log.d(TAG, "MD5 File: " + MD5filetodelete.getAbsolutePath());
            }
            ZIPfiletodelete = null;
            MD5filetodelete = null;

            success = true;
            Toast.makeText(this, MessageFormat.format(getResources().getString(R.string.delete_single_update_success_message), filename), Toast.LENGTH_LONG).show();
        } else if (!mUpdateFolder.exists()) {
            Toast.makeText(this, R.string.delete_updates_noFolder_message, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, R.string.delete_updates_failure_message, Toast.LENGTH_LONG).show();
        }
        return success;
    }
    
    private void deleteOldAppData() {
        if (mDataFolder.exists() && mDataFolder.isDirectory()) {
        	deleteDir(mDataFolder);
        	Log.d(TAG, "Old Data Folder Deleted");
        	Toast.makeText(this, R.string.delete_app_data_success_message, Toast.LENGTH_SHORT).show();
        } else if (!mDataFolder.exists()) {
        	Toast.makeText(this, R.string.delete_app_data_noFolder_message, Toast.LENGTH_SHORT).show();
        } else {
        	Toast.makeText(this, R.string.delete_app_data_failure_message, Toast.LENGTH_LONG).show();
        }
    }
    
    private void checkForOldAppData() {
    	int version = -1;
    	try {
    		PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
    		version = pi.versionCode;
    			} catch (Exception e) {
    		if (showDebugOutput) Log.e(TAG, "Package name not found", e);
    	}
    	long currentAppVersion = version;
    	long storedVersion = prefs.getStoredVersion();
    	mDataFolder = new File("/data/data/" + Customization.PACKAGE_FIRST_NAME + ".ui");
    	if (mDataFolder.exists() && mDataFolder.isDirectory()) {
    		if (storedVersion > 0 && currentAppVersion > 0 && currentAppVersion < storedVersion) {
    			return;
    			} else {
    			showDialog(DIALOG_OLD_APP_FILES);
    		}
    	}
    }

    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }
        // The directory is now empty so delete it
        return dir.delete();
    }
    
    private void collectAndSendLog() {
        final PackageManager packageManager = getPackageManager();
        final Intent intent = new Intent(Constants.ACTION_SEND_LOG);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        final boolean isInstalled = list.size() > 0;
        
        if (!isInstalled){
            showDialog(DIALOG_LOG_COLLECTOR_NOT_INSTALLED);
        }
        else{
        	showDialog(DIALOG_BUG_REPORTER_SEND_LOG);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_NO_SDCARD:
                return new AlertDialog.Builder(this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.sdcard_is_not_present_dialog_title)
                        .setMessage(R.string.sdcard_is_not_present_dialog_body)
                        .setPositiveButton(R.string.sdcard_is_not_present_dialog_ok_button, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
            case DIALOG_OVERWRITE_UPDATE:
                return new AlertDialog.Builder(this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.overwrite_update_title)
                        .setMessage(R.string.overwrite_update_summary)
                        .setNegativeButton(R.string.overwrite_update_negative, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton(R.string.overwrite_update_positive, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                foo.delete();
                                if (showDebugOutput)
                                    Log.d(TAG, "Start downlading update: " + updateForDownload.getFileName());
                                downloadRequestedUpdate(updateForDownload);
                            }
                        }).create();
            case DIALOG_DELETE_EXISTING:
                return new AlertDialog.Builder(this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.delete_updates_text)
                        .setMessage(R.string.confirm_delete_update_folder_dialog_message)
                                //Delete Only Selected Update
                        .setNeutralButton(R.string.confirm_delete_update_folder_dialog_neutral, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //Delete Updates here
                                String f = (String) mExistingUpdatesSpinner.getSelectedItem();
                                if (showDebugOutput) Log.d(TAG, "Delete single Update selected: " + f);
                                deleteUpdate(f);
                                updateLayout();
                            }
                        })
                                //Delete All Updates
                        .setPositiveButton(R.string.confirm_delete_update_folder_dialog_yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (showDebugOutput) Log.d(TAG, "Delete all Updates selected");
                                //Delete Updates here
                                //Set the Filenames to null, so the Spinner will be empty
                                deleteOldUpdates();
                                updateLayout();
                            }
                        })
                                //Delete no Update
                        .setNegativeButton(R.string.confirm_delete_update_folder_dialog_no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (showDebugOutput) Log.d(TAG, "Delete no updates selected");
                                dialog.dismiss();
                            }
                        }).create();
            case DIALOG_RUNNING_OLD_VERSION:
                return new AlertDialog.Builder(MainActivity.this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.alert_old_version_title)
                        .setMessage(R.string.alert_old_version_summary)
                        .setNeutralButton(R.string.alert_old_version_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(R.string.alert_old_version_browser, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //Open the Browser for Instructions
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(getString(R.string.update_instructions_url)));
                                startActivity(i);
                                dialog.dismiss();
                            }
                        }).create();
            case DIALOG_NO_MD5:
                return new AlertDialog.Builder(MainActivity.this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.no_md5_found_title)
                        .setMessage(R.string.no_md5_found_summary)
                        .setPositiveButton(R.string.no_md5_found_positive, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //Directly call on Postexecute, cause we need no md5check
                                new MD5CheckerTask(MainActivity.this, null, existingUpdateFilename, existingUpdateFilenotes, showDebugOutput).onPostExecute(true);
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(R.string.no_md5_found_negative, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
            case DIALOG_ABOUT:
            	LayoutInflater li = LayoutInflater.from(this);
                View view = li.inflate(R.layout.about, null); 
                TextView mVersionName = (TextView)view.findViewById(R.id.versionName);
                TextView mModVersionName = (TextView)view.findViewById(R.id.ModVersionName);
                mModVersionName.setText(SysUtils.getModVersion());
                try {
                    PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
                    mVersionName.setText(res.getString(R.string.app_name) + "-" + pi.versionName);
                }
                catch (NameNotFoundException e) {
                    if (showDebugOutput) Log.e(TAG, "Can't find version name", e);
                    mVersionName.setText("- Unknown -");
                }
        		return new AlertDialog.Builder(MainActivity.this)
        				.setIcon(android.R.drawable.ic_dialog_info)
                		.setTitle(R.string.about_dialog_title)
                		.setView(view)
                		.setPositiveButton(R.string.about_donate_button, new DialogInterface.OnClickListener() {
                        	public void onClick(DialogInterface dialog, int whichButton) {
                                if (Customization.DualDevsupport) { 
                                	showDialog (DIALOG_DUAL_DONATION);
                                } else {
                                	Uri uri = Uri.parse(getString(R.string.paypal_url_dev_one));
                                	startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                	dialog.dismiss();
                                }
                        	}
                		})
                		.setNeutralButton(R.string.welcome_tutorial, new DialogInterface.OnClickListener() {
                        	public void onClick(DialogInterface dialog, int whichButton) {
                                Uri uri = Uri.parse(getString(R.string.app_tutorial_url));
                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                dialog.dismiss();
                        	}
                		})
                		.setNegativeButton(R.string.about_close_button, new DialogInterface.OnClickListener() {
                        	public void onClick(DialogInterface dialog, int whichButton) {
                                dialog.dismiss();
                        	}
                		}).create();
            case DIALOG_NO_SDCARD_START:
                return new AlertDialog.Builder(this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.sdcard_is_not_present_dialog_title)
                        .setMessage(R.string.sdcard_is_not_present_start_body)
                        .setPositiveButton(R.string.sdcard_is_not_present_dialog_ok_button, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
            case DIALOG_OLD_APP_FILES:
                return new AlertDialog.Builder(this)
                		.setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.alert_delete_old_files_title)
                        .setMessage(R.string.alert_delete_old_files_summary)
                        .setCancelable(false)
                        .setPositiveButton(R.string.alert_delete_old_files_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            	prefs.resetAppDataWipePref();
                            	deleteOldAppData();
                            	finish();
                            }
                        }).create();
            case DIALOG_FIRST_START:
                return new AlertDialog.Builder(MainActivity.this)
                        .setTitle(res.getString(R.string.welcome_title) + " " + res.getString(R.string.app_name))
                        .setMessage(R.string.welcome_summary)
                        .setPositiveButton(R.string.welcome_changelog, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            	getChangelog(ChangelogType.APP);
                            	dialog.dismiss();
                            }
                        })
                        .setNeutralButton(R.string.welcome_tutorial, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            	Uri uri = Uri.parse(getString(R.string.app_tutorial_url));
                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton(R.string.welcome_close, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                             }
                        }).create();
            case DIALOG_LOG_COLLECTOR_NOT_INSTALLED:
                return new AlertDialog.Builder(MainActivity.this)
                		.setIcon(android.R.drawable.ic_dialog_alert)		
                		.setTitle(R.string.bug_reporter_installed_title)
                		.setMessage(R.string.bug_reporter_install_summary)
                		.setPositiveButton(R.string.bug_reporter_ok, new DialogInterface.OnClickListener(){
                			public void onClick(DialogInterface dialog, int whichButton){
                				Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + Constants.LOG_COLLECTOR_PACKAGE_NAME));
                				marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                				startActivity(marketIntent); 
                			}
                		})
                		.setNegativeButton(R.string.bug_reporter_cancel, new DialogInterface.OnClickListener() {
                			public void onClick(DialogInterface dialog, int which) {
                				dialog.dismiss();
                			}
                      }).create();
            case DIALOG_BUG_REPORTER_SEND_LOG:
            	final Intent intent = new Intent(Constants.ACTION_SEND_LOG);
            	mAdditonalInfo = getString(R.string.bug_reporter_device_info, SysUtils.getVersionNumber(this), SysUtils.getModVersion(), Build.MODEL, 
            			Build.VERSION.RELEASE, Build.DISPLAY, SysUtils.getFormattedKernelVersion());
                return new AlertDialog.Builder(MainActivity.this)
                		.setIcon(android.R.drawable.ic_dialog_info)
                		.setTitle(R.string.bug_reporter_title)
                		.setMessage(R.string.bug_reporter_summary)
                		.setPositiveButton(R.string.bug_reporter_ok, new DialogInterface.OnClickListener(){
                			public void onClick(DialogInterface dialog, int whichButton) {
                				if (!prefs.displayDebugOutput()) {
                					Toast.makeText(getApplicationContext(), R.string.bug_reporter_debug_false, Toast.LENGTH_SHORT).show();
                				} else {
                					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                					intent.putExtra(Constants.EXTRA_SEND_INTENT_ACTION, Intent.ACTION_SENDTO);
                					final String email = getString(R.string.bug_reporter_email);
                					intent.putExtra(Constants.EXTRA_DATA, Uri.parse("mailto:" + email));
                					intent.putExtra(Constants.EXTRA_ADDITIONAL_INFO, mAdditonalInfo);
                					intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.bug_reporter_fail_info));
                					intent.putExtra(Constants.EXTRA_FORMAT, "time");
                					String[] filterSpecs = new String[3];
                					filterSpecs[0] = "AndroidRuntime:D" + "AndroidRuntime:E" + "AndroidRuntime:I" + "AndroidRuntime:V";
                					filterSpecs[1] = Log.LOGTAG;
                					filterSpecs[2] = "*:S";
                					intent.putExtra(Constants.EXTRA_FILTER_SPECS, filterSpecs);
                        
                					startActivity(intent);
                				}
                			}
                		})
                		.setNegativeButton(R.string.bug_reporter_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                             }
                	}).create();
            case DIALOG_DUAL_DONATION:
            	LayoutInflater Li = LayoutInflater.from(this);
                View mView = Li.inflate(R.layout.donation, null); 
        		return new AlertDialog.Builder(MainActivity.this)
        				.setIcon(android.R.drawable.ic_dialog_info)
                		.setTitle(R.string.donate_dialog_title)
                		.setView(mView)
                		.setPositiveButton(R.string.dev_one_name, new DialogInterface.OnClickListener() {
                        	public void onClick(DialogInterface dialog, int whichButton) {
                                Uri uri = Uri.parse(getString(R.string.paypal_url_dev_one));
                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                dialog.dismiss();
                                
                        	}
                		})
                		.setNeutralButton(R.string.dev_two_name, new DialogInterface.OnClickListener() {
                        	public void onClick(DialogInterface dialog, int whichButton) {
                                Uri uri = Uri.parse(getString(R.string.paypal_url_dev_two));
                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                dialog.dismiss();
                        	}
                		}).create();
            default:
                return null;
        }
    }
}